package com.yxp423.ssmempl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.yxp423.ssmempl.bean.User;
import com.yxp423.ssmempl.bean.dto.UserOnline;
import com.yxp423.ssmempl.service.ISessionService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Description: java类作用描述
 * @Author: yxp
 * @CreateDate: 2019-05-07 20:03
 * @Version: 1.0
 */
@Service
public class SessionServiceImpl implements ISessionService {


	@Autowired
	private  SessionDAO sessionDAO;


	@Override
	public List<UserOnline> getOnlineUsers(HttpServletRequest request) {

		List<UserOnline> onlineList = new ArrayList<>();

		Collection<Session> sessions = sessionDAO.getActiveSessions();//获取所有有效的Session

		for (Session session : sessions) {

			UserOnline userOnline = new UserOnline();
			User user;

			SimplePrincipalCollection principalCollection ;

			if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
				continue;
			}else {

				principalCollection = (SimplePrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);

				user = (User) principalCollection.getPrimaryPrincipal();

				userOnline.setUsername(user.getName());
				userOnline.setUserId(user.getUserId().toString());
			}

			userOnline.setId(session.getId().toString());

			String host = StrUtil.equals(session.getHost(),"0:0:0:0:0:0:0:1") ? "127.0.0.1" : session.getHost();
			userOnline.setHost(host);
			userOnline.setUserAgent(request.getHeader("user-agent"));

			userOnline.setStartTimestamp(session.getStartTimestamp());
			userOnline.setLastAccessTime(session.getLastAccessTime());

			long timeout = session.getTimeout();

			if (timeout == 0l) {
				userOnline.setStatus("离线");
			} else {
				userOnline.setStatus("在线");
			}
			userOnline.setTimeout(timeout);
			onlineList.add(userOnline);

		}




		return onlineList;
	}

	@Override
	public boolean kickOut(String sessionId) {
		Session session = sessionDAO.readSession(sessionId);
		sessionDAO.delete(session);
		session.setTimeout(0);
		return true;
	}
}
